<?php

    class IndexController extends Zend_Controller_Action
    {

        private $user_id;
        private $user;
        private $commonModel;

        function init()
        {
            
            $this->commonModel = new Application_Model_Common();
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if (!empty($y))
                $this->user_id = $x->read()->rkn_uid;
            $this->user = (array) $y;
        }

        function indexAction()
        {
            $brand_features = $this->commonModel->getAdapter()->select()->from("rkn_brand")
                    ->join("rkn_product", "rkn_product.brand_id = rkn_brand.brand_id ")
                    ->where("status='1' and brand_status = '1' ")
                    ->group("rkn_brand.brand_id")
                    ->order("rkn_brand.brand_id desc")
            ;
            $brand_features = $brand_features->query()->fetchAll();
            $this->view->brandFeatures = $brand_features;
            
            
            
        }

        function blogAction()
        {
            $model = new Application_Model_Common();
            $this->_helper->layout->disableLayout();
//            $blog_id = $this->_getParam("blog_id");
            $blog_id = getEncryptedString($this->_getParam(getEncryptedString("blog_id")), "decode");
//            prd($blog_id);
            $blog_records = $model->getAllRecordFromLeftJoin(array("b" => "rkn_blog"), array("u" => "rkn_user"), "u.rkn_uid=b.blog_creator", "blog_id =  " . $blog_id, "b.blog_id DESC");
            $this->view->assign($blog_records[0]);
            $comments = $model->getAllRecordFromLeftJoin(RKN_BLOG_COMMENT, RKN_USER, RKN_USER . ".rkn_uid = " . RKN_BLOG_COMMENT . ".comment_user_id", "comment_blog_id = " . $blog_id . " and comment_status = '1'", " comment_id desc", "2");
            $blogArr = $model->getAllRecordDetail(RKN_BLOG, "blog_status = '1' ", "blog_id desc");
            //prd($blogArr);
            $next_url = false;
            $prev_url = true;

            $this->view->next_url = $this->view->prev_url = 'javascript:;';
            //javascript:parent.jQuery.fancybox.open({href : '1_b.jpg', title : 'My title'});

            foreach ($blogArr as $val)
            {
                if ($next_url)
                    $this->view->next_url = "window.parent.$('#blog-" . $val['blog_id'] . "').click();window.parent.jQuery.fancybox.close();";
                //APPLICATION_URL."/index/blog/blog_id/".$val['blog_id'];
                if ($prev_url && $val['blog_id'] != $blog_id)
                    $this->view->prev_url = "window.parent.$('#blog-" . $val['blog_id'] . "').click();window.parent.jQuery.fancybox.close();";
                //APPLICATION_URL."/index/blog/blog_id/".$val['blog_id'];
                if ($val['blog_id'] == $blog_id)
                {
                    $next_url = true;
                    $prev_url = false;
                }
            }
            //   prd($this->view->next_url);
            $this->view->comments = $comments;

            $showPrevButton = "yes";
            $showNextButton = "yes";

            if ($this->getParam("prev"))
            {
                $showPrevButton = "no";
            }
            if ($this->getParam("next"))
            {
                $showNextButton = "no";
            }

            $this->view->showNextButton = $showNextButton;
            $this->view->showPrevButton = $showPrevButton;
        }

        function registerAction()
        {
            $this->_helper->layout()->disableLayout();
            $form = new Application_Form_SettingForm();
            $this->view->signupForm = $form;
            $flag = array();
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                unset($arr['submit']);
                if ($form->isValid($arr))
                {
                    {

                        $arr['ipaddress'] = $_SERVER["REMOTE_ADDR"];
                        $uid = $this->commonModel->insertRecordData($arr, RKN_USER);
                        $emailModel = new Application_Model_Email();
                        $siteConfig = Zend_Registry::get('SITE_CONFIG');
                        $fromEmail = $siteConfig['site_email'];
                        $fromName = $siteConfig['site_name'];
                        $subject = "Thanks for joining us";
//                        $url = APPLICATION_URL . "/index/index/tokenId/" . sha1($uid);
//                        $message = "
//				Hi " . $arr['first_name'] . " " . $arr['last_name'] . ",
//				<br>
//				Thanks for signing up and welcome to the Raeken community!
//				<br>
//				We'd love to hear from you at " . $fromEmail . " please <a href='" . $url . "'>Click Here</a> to activate your account.
//				<br>
//				Happy Shopping.
//				<br>
//				The Raeken Team
//				<br>			
//				";
//                        $message = "Congragulations! <br> your email is registered. We will let you know when we go live";
//                        if (IS_LIVE)
                        if ($_SERVER["REMOTE_ADDR"] != '127.0.0.1')
                        {
                            $unsubscribe_url = "#";
                            $fbShareUrl = "#";
                            $twitterShareUrl = "#";
                            $message = $emailTemplate = $emailModel->newRegisterationEmailTemplate($arr["username"], $arr["first_name"], $unsubscribe_url, $fbShareUrl, $twitterShareUrl);
                            $emailModel->sendMail($arr['email_address'], $fromEmail, $fromName, $subject, $message);
                        }

//                        $this->_helper->FlashMessenger(
//                                array('success' => '<strong>Success!</strong> You have successfully registered your account your activation. Your activation mail has been sent to your email account')
//                        );

                        $flag['error'] = false;
                        $flag['success'] = true;
//                        $flag['message'] = "<strong>Success!</strong><br>
//                                            You have successfully registered your account your activation.<br>
//                                            Your activation mail has been sent to your email account.";
                        $flag['message'] = "<strong>Congratulations!</strong>&nbsp;your email is registered. We will let you know when we go live";


                        $this->view->assign($flag);
                        //$this->_redirect("index/signup");
                    }
//                    else
//                    {
//
//                        $flag['error'] = true;
//                        $flag['success'] = false;
//                        $flag['message'] = "<strong>Oops!</strong>
//                                            Your email is already registered.";
//
//                        $this->view->assign($flag);
//                    }
                }
                else
                {
                    $flag['error'] = true;
                    $flag['success'] = false;
                    $flag['message'] = "<strong>Oops!</strong>
                                            Please fill all the required fields with proper information";

                    $this->view->assign($flag);
                }
            }
        }

        function signupAction()
        {
            $this->_helper->layout()->disableLayout();
            $form = new Application_Form_SignupForm();
            $this->view->signupForm = $form;
            $flag = array();
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                unset($arr['submit']);
                if ($form->isValid($arr))
                {
                    $validator = new Zend_Validate_Db_NoRecordExists(
                                    array(
                                        'table' => RKN_USER,
                                        'field' => 'email_address'
                                    )
                    );

                    if ($validator->isValid($arr['email_address']))
                    {
                        $arr['password'] = md5($arr['password']);
                        $arr['ipaddress'] = $_SERVER["REMOTE_ADDR"];
//                        echo '<pre>';
//                        print_r($arr);
//                        die;
                        $uid = $this->commonModel->insertRecordData($arr, RKN_USER);
                        $emailModel = new Application_Model_Email();
                        $siteConfig = Zend_Registry::get('SITE_CONFIG');
                        $fromEmail = $siteConfig['site_email'];
                        $fromName = $siteConfig['site_name'];
                        $subject = "Thanks for joining us";
                        $url = APPLICATION_URL . "/index/index/tokenId/" . sha1($uid);
                        $message = "
				Hi " . $arr['first_name'] . " " . $arr['last_name'] . ",
				<br>
				Thanks for signing up and welcome to the Raeken community!
				<br>
				We'd love to hear from you at " . $fromEmail . " please <a href='" . $url . "'>Click Here</a> to activate your account.
				<br>
				Happy Shopping.
				<br>
				The Raeken Team
				<br>			
				";

                        $message = "Congragulations! <br> your email is registered. We will let you know when we go live";

                        if ($_SERVER["REMOTE_ADDR"] != '127.0.0.1')
                            $emailModel->sendMail($arr['email_address'], $fromEmail, $fromName, $subject, $message);

//                        $this->_helper->FlashMessenger(
//                                array('success' => '<strong>Success!</strong> You have successfully registered your account your activation. Your activation mail has been sent to your email account')
//                        );

                        $flag['error'] = false;
                        $flag['success'] = true;
                        $flag['message'] = "<strong>Success!</strong><br>
                                            You have successfully registered your account your activation.<br>
                                            Your activation mail has been sent to your email account.";


                        $this->view->assign($flag);
                        //$this->_redirect("index/signup");
                    }
                    else
                    {

                        $flag['error'] = true;
                        $flag['success'] = false;
                        $flag['message'] = "<strong>Oops!</strong>
                                            Your email is already registered.";

                        $this->view->assign($flag);
                    }
                }
                else
                {
                    $flag['error'] = true;
                    $flag['success'] = false;
                    $flag['message'] = "<strong>Oops!</strong>
                                            Please fill all the required fields with proper information";

                    $this->view->assign($flag);
                }
            }
        }

        function loginAction()
        {

            if(!empty($this->user_id))
                $this->_redirect("");
            
            $form = new Application_Form_LoginForm(array('step'=>'main'));
            $fo = $this->getRequest()->getPost('form');
            if ($this->getRequest()->isPost() && $fo == 'login')
            {
                $arr = $this->getRequest()->getPost();
                if ($form->isValid($arr))
                {
                    //============login process starts================
                    $db = Zend_Registry::get('db');
                    $authAdapter = new Zend_Auth_Adapter_DbTable(
                                    $db, RKN_USER, 'email_address', 'password', 'MD5(?) '
                    );

                    $authAdapter->setIdentity($arr['email_address'])
                            ->setCredential($arr['password']);

                    $zend_auth = Zend_Auth::getInstance();
                    $result = $zend_auth->authenticate($authAdapter);
                    if ($result->isValid())
                    {
                        $user = $authAdapter->getResultRowObject(null, 'user_password');
                        //check if the account is activated or not
//                        prd($user);
                        if ($user->status != '1')
                        {


                            $this->_helper->FlashMessenger(
                                    array('error' => '<strong>Oops!</strong> Your account is not activated yet!')
                            );
                            
                            $this->_redirect("index/login");
                        }
                        else
                        {
                            $zend_auth->setStorage(new Zend_Auth_Storage_Session('User_Auth'));
                            $storage = $zend_auth->getStorage();
                            $storage->write($user);
                            $this->_redirect("");
                            
                        }
                    }
                    else
                    {
                        
                        $this->_helper->FlashMessenger(
                                array('error' => '<strong>Oops!</strong> Username or password is incorrect')
                        );
                        $this->_redirect("");
                    }
                    //------------login process ends------------------
                }
                else
                {
                        $this->_helper->FlashMessenger(
                                array('error' => "<strong>Oops!</strong> Please enter correct information.<br>")
                        );

                        $this->_redirect("index/login");

                }
            }
            $this->view->loginForm = $form;
        }

        public function logoutAction()
        {
            $auth = Zend_Auth::getInstance();
            $auth->clearIdentity();
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $x->clear();

            $this->_helper->FlashMessenger(
                    array('success' => 'You have successfully logged out')
            );
            $this->_redirect("");
        }

        function forgotpasswordAction()
        {
            $this->_helper->layout()->disableLayout();
            $form = new Application_Form_ForgotpasswordForm();
            $this->view->forgotPasswordForm = $form;

            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $user_email = $arr["email_address"];

                if ($form->isValid($arr))
                    $is_exists = $this->commonModel->is_exists(RKN_USER, "email_address = '$user_email'");

                if (empty($is_exists))
                {
                    $flag['error'] = true;
                    $flag['success'] = false;
                    $flag['message'] = "<strong>Oops!</strong><br>
                                        Your email address is not found in system<br>
                                        if you want to join us so please register";

                    $this->view->assign($flag);
                }
                else
                {
                    //  new password and send email    
                    $new_password = strtoupper(substr(md5(time()), 0, 8));

                    $email_model = new Application_Model_Email();

                    $site_config = Zend_Registry::get('SITE_CONFIG');
                    $toEmail = $user_email;
                    $fromEmail = $site_config['site_email'];
                    $fromName = $site_config['site_name'];
                    $subject = 'Password Reset';
                    $messageContent = "Your new password is <strong>$new_password</strong>";

                    if ($_SERVER["REMOTE_ADDR"] != '127.0.0.1')
                        $email_model->sendMail($toEmail, $fromEmail, $fromName, $subject, $messageContent);

//                    if (IS_LIVE)
//                        $sendEmail = $email_model->sendMail($toEmail, $fromEmail, $fromName, $subject, $messageContent);

                    $this->commonModel->updateRecordData(array("password" => md5($new_password)), "email_address = '$user_email'", RKN_USER);
                    $flag['error'] = false;
                    $flag['success'] = true;
                    $flag['message'] = "<strong>Success!</strong><br>
                                        Your new password has been sent to your email address";

                    $this->view->assign($flag);
                }
            }
        }

        // 06:23 AM 04/03/2013
        public function forgotAction()
        {
            global $mySession;
            $db = new Db();
            $email_addr = mysql_escape_string($_REQUEST['forgot_email']);
            $status = mysql_escape_string($_REQUEST['status']);
            if (isset($email_addr) && ($status == 200))
            {
                $chkUserInfo = $db->runQuery("select * from `rkn_user` where `email_address`='" . $email_addr . "'");
                if ($chkUserInfo[0]['status'] == '0')
                {
                    $arr['message'] = 'Sorry you are not able to send password request.';
                    $arr['status'] = '200';
                    echo json_encode($arr);
                    exit;
                }
                else if (isset($chkUserInfo[0]['email_address']))
                {
                    $url = APPLICATION_URL;
                    $message = "<html>
				<head>
				<title>Welcome to Raeken</title>
				</head>
				<body>
				Hi " . $chkUserInfo[0]['email_address'] . ",
				<br>
				Your password for raeken login are $chkUserInfo[0]['tmp_pass']
				<br>
				We'd love to hear from you at info@raeken.com please <a href=" . $url . ">Click Here</a> to login your account.
				<br>
				Happy Shopping.
				<br>
				The Raeken Team
				<br>			
				</body>
				</html>";
                    $subject = "Raeken Forgot Password";
                    // Always set content-type when sending HTML email
                    $headers = "MIME-Version: 1.0" . "\r\n";
                    $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";

                    // More headers
                    $headers .= 'From: <noreply@raeken.com>' . "\r\n";
                    $headers .= 'Cc: info@raeken.com' . "\r\n";
                    mail($to, $subject, $message, $headers);
                    $arr['message'] = 'Password send to your email address please check your email address.';
                    $arr['status'] = '201';
                    echo json_encode($arr);
                    exit;
                }
                else
                {
                    $arr['message'] = 'Your email address is not found in system if you want to join us so please click on signup.';
                    $arr['status'] = '202';
                    echo json_encode($arr);
                    exit;
                }
            }
        }

        // 09:17 PM 04/03/2013
        public function brandprocessingAction()
        {
            global $mySession;
            $db = new Db();

            // Prevent From Sql Injection
            $brand_name = mysql_escape_string($_REQUEST['brand_name']);
            $brand_login_name = mysql_escape_string($_REQUEST['brand_login_name']);
            $brand_email = mysql_escape_string($_REQUEST['brand_email']);
            $brand_password = mysql_escape_string($_REQUEST['brand_password']);
            $status = mysql_escape_string($_REQUEST['status']);
            if (isset($brand_name) && isset($brand_password) && isset($status))
            {
                // Check User information available
                $checkUser = $db->runQuery("select * from `rkn_brand` where `brand_email`='" . $brand_email . "' OR `brand_name`='" . $brand_name . "'");
                if (isset($checkUser[0]['email_address']))
                {
                    $credential['status'] = '500';
                    $credential['message'] = 'Brand already register please click on forgot password.';
                    $credential['date'] = date('Y-m-d h:i:s a');
                    $credential['encId'] = base64_encode($email_address);
                    // Json Encode this array into json string
                    echo json_encode($credential);
                    exit;
                }
                else
                {
                    $saveCred['brand_name'] = $brand_name;
                    $saveCred['brand_login_name'] = $brand_login_name;
                    $saveCred['brand_email'] = $brand_email;
                    $saveCred['brand_password'] = md5($brand_password);
                    $saveCred['brand_social_connection'] = '';
                    $saveCred['brand_social_on'] = '0';
                    $saveCred['ip_addr'] = $_SERVER['REMOTE_ADDR'];
                    $saveCred['brand_video'] = '';
                    $saveCred['brand_photo'] = '';
                    $saveCred['brand_desc'] = '';
                    $saveCred['brand_keywords'] = '';
                    $saveCred['brand_brief_desc'] = '';
                    $saveCred['brand_status'] = '0';
                    $saveCred['tmp_pass'] = $brand_password;
                    $db->save('rkn_brand', $saveCred);
                    $credential['status'] = '200';
                    $credential['message'] = 'Thank you for registration please check your email address.';
                    $credential['date'] = date('Y-m-d h:i:s a');
                    $credential['encId'] = base64_encode($brand_email);
                    $credential['sessId'] = sha1($brand_email);
                    $to = $brand_email;
                    $url = APPLICATION_URL . 'index/confirmbrand/tokenId/' . sha1($db->lastInsertId());
                    $message = "
				<html>
				<head>
				<title>Welcome to Raeken</title>
				</head>
				<body>
				Hi " . $brand_name . ",
				<br>
				Thanks for signing up and welcome to the Raeken community!
				<br>
				We'd love to hear from you at info@raeken.com please <a href=" . $url . ">Click Here</a> to activate your account.
				<br>
				Happy Shopping.
				<br>
				The Raeken Team
				<br>			
				</body>
				</html>";
                    $subject = "Congrats! Your Account is Created Successfully";
                    // Always set content-type when sending HTML email
                    $headers = "MIME-Version: 1.0" . "\r\n";
                    $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";

                    // More headers
                    $headers .= 'From: <noreply@raeken.com>' . "\r\n";
                    $headers .= 'Cc: info@raeken.com' . "\r\n";
                    mail($to, $subject, $message, $headers);
                    echo json_encode($credential);
                    exit;
                    // Json Encode this array into json string
                }
            }
        }

        // 09:31 PM 04/07/2013
        public function confirmbrandAction()
        {
            global $mySession;
            $db = new Db();
            // user id in encrypted format
            $tokenId = $this->getRequest()->getParam('tokenId');
            if (isset($tokenId))
            {
                // sha1 use in encrypted format
                $chkUser = $db->runQuery("select `brand_id`,`brand_status` from `rkn_brand` where sha1(`brand_id`)='" . $tokenId . "'");
                if (isset($chkUser[0]['brand_id']))
                {
                    if ($chkUser[0]['brand_status'] == '0')
                    {
                        $update['brand_status'] = '1';
                        $condition = "brand_id=" . $chkUser[0]['brand_id'];
                        $result = $db->modify('rkn_brand', $update, $condition);
                        if ($result == '1')
                        {
                            $mySession->errorMsg = "Your account is activate successfully.";
                            $this->_redirect(APPLICATION_URL);
                        }
                        else
                        {
                            $mySession->errorMsg = "Sorry Your account is not activate now.";
                            $this->_redirect(APPLICATION_URL);
                        }
                    }
                    else
                    {
                        $mySession->errorMsg = "Sorry this link already activated.";
                        $this->_redirect(APPLICATION_URL);
                    }
                }
                else
                {
                    $mySession->errorMsg = "Sorry you are not authorize user.";
                    $this->_redirect(APPLICATION_URL);
                }
            }
        }

        // 04:04 PM 08/07/2013
        public function checkbrandcredentialAction()
        {
            global $mySession;
            $db = new Db();
            $loginEmail = mysql_escape_string($_REQUEST['brand_login_name']);
            $loginpassword = mysql_escape_string($_REQUEST['login_password']);
            $status = mysql_escape_string($_REQUEST['status']);
            if (isset($loginEmail) && isset($loginpassword) && ($status == 200))
            {
                $chkCredential = $db->runQuery("select * from `rkn_brand` where `brand_login_name`='" . $loginEmail . "' and `brand_password`='" . md5($loginpassword) . "' and `brand_status`='1'");
                if ($chkCredential[0]['brand_id'])
                {
                    // Now create session for valid user
                    // for User Id
                    $mySession->rknBrandid = $chkCredential[0]['brand_id'];
                    // for User Email Address
                    $mySession->rknBrandEmailId = $chkCredential[0]['brand_email'];
                    $mySession->rknBrandName = $chkCredential[0]['brand_name'];
                    $mySession->brand_id = rand(time(), time());
                    $mySession->encbrand_id = substr(sha1(rand(time(), time())), 10, 24);
                    // for success login
                    $arr['message'] = 'You have valid authenticate.';
                    $arr['code'] = 'VCode';
                    $arr['status'] = 200;
                    echo json_encode($arr);
                    exit;
                }
                else
                {
                    // Sorry you are not valid user
                    $arr['message'] = 'You are not valid user.';
                    $arr['code'] = 'ECode';
                    $arr['status'] = 201;
                    echo json_encode($arr);
                    exit;
                }
            }
            else
            {
                // You are not authorize
                $arr['message'] = 'You are not authorize user.';
                $arr['code'] = 'ACode';
                $arr['status'] = 202;
                echo json_encode($arr);
                exit;
            }
        }

// 05:17 PM 17/06/2013
        public function searchAction()
        {
            global $mySession;
            $db = new Db();
            $searchWord = mysql_escape_string($_REQUEST['searchKey']);
            $action = mysql_escape_string($_REQUEST['action']);
            if (isset($searchWord) && ($action == 'search'))
            {
                $category = $db->runQuery("select `cat_name`,`cat_id` from `rkn_category` where (`cat_name` LIKE '%" . $searchWord . "') OR (`cat_name` LIKE '%" . $searchWord . "%') OR (`cat_name` LIKE '" . $searchWord . "%') LIMIT 0,10");
                $brand = $db->runQuery("select `brand_id`,`brand_name` from `rkn_brand` where (`brand_name` LIKE '%" . $searchWord . "') OR (`brand_name` LIKE '%" . $searchWord . "%') OR (`brand_name` LIKE '" . $searchWord . "%') LIMIT 0,10");
                $product = $db->runQuery("select rkn_prod_id,`prod_name` from `rkn_product` where (`prod_name` LIKE '%" . $searchWord . "') OR (`prod_name` LIKE '%" . $searchWord . "%') OR (`prod_name` LIKE '" . $searchWord . "%') LIMIT 0,10");
                ?>
                <script type="text/javascript">
                    $(document).ready(function(e) {
                        $("a.clickable").click(function(e) {
                            $('#hid').val($(this).attr('id'));
                            $("#search_box").val($(this).html());
                        });
                    });
                </script>
                <input type="hidden" name="hid" id="hid" />
                <?php
                if (count($category) != 0)
                {
                    ?>
                    <ul class="searchList">
                        <li id="cat">Search Categories</li>
                        <?
                        for ($i = 0; $i < count($category); $i++)
                        {
                            echo '<li><a class="clickable" style="color:#fff;text-decoration:none;" id="c' . $category[$i]['cat_id'] . '">' . $category[$i]['cat_name'] . '</a></li>';
                        }
                        ?>
                    </ul>
                    <?php
                }
                ?>
                <?php
                if (count($brand) != 0)
                {
                    ?>
                    <ul class="searchList">
                        <li id="cat">Search Brand</li>
                        <?
                        for ($j = 0; $j < count($brand); $j++)
                        {
                            echo '<li><a class="clickable" style="color:#fff;text-decoration:none;" id="b' . $brand[$j]['brand_id'] . '">' . $brand[$j]['brand_name'] . '</a></li>';
                        }
                        ?>
                    </ul>
                    <?php
                }
                ?>
                <?php
                if (count($product) != 0)
                {
                    ?>
                    <ul class="searchList">
                        <li id="cat">Search Products</li>
                        <?
                        for ($k = 0; $k < count($product); $k++)
                        {
                            echo '<li><a class="clickable" style="color:#fff;text-decoration:none;" id="p' . $product[$k]['rkn_prod_id'] . '">' . $product[$k]['prod_name'] . '</a></li>';
                        }
                        ?>
                    </ul>
                    <?php
                }exit;
                ?>
                <?
            }
            else
            {
                $error['status'] = 'Sorry you are not authorize.';
                $error['code'] = '403';
                $error['trace'] = base64_encode($_SERVER['REMOTE_ADDR']);
                $error['time'] = time();
                echo json_encode($error);
                exit;
            }
        }

        public function postcommentajaxAction()
        {
            if ($this->getRequest()->isPost())
            {
                $model = new Application_Model_Common();
                $arr = $this->getRequest()->getPost();
                $comment_text = $arr["comment_text"];
                $blog_id = $arr["blog_id"];
                $user_id = "0";
                if (isset($arr["user_name"]))
                    $user_name = trim($arr["user_name"]);
                else
                {
                    $user_id = $x->read()->user_id;
                    $user_name = $x->read()->first_name . " " . $x->read()->last_name;
                }
                $x = new Zend_Auth_Storage_Session('User_Auth');
                $y = $x->read();
                if (!empty($y))
                {
                    $user_id = $x->read()->user_id;
                    $user_name = $x->read()->first_name . " " . $x->read()->last_name;
                }
                $data_array = array(
                    "comment_blog_id" => $blog_id,
                    "comment_user_id" => $user_id,
                    "comment_nickname" => $user_name,
                    "comment_text" => $comment_text
                );
                $model->insertRecordData($data_array, "rkn_blog_comment");
                $this->_helper->FlashMessenger(
                        array('success' => '<strong>Success!</strong> Your comment has been sent for admin approval')
                );
            }
            die;
        }

        public function adduserfromcommentAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
//                prd($arr);
                unset($arr["comment_text"]);
                $arr['password'] = md5($arr['password']);
                $arr['ip'] = $_SERVER["REMOTE_ADDR"];
                $uid = $this->commonModel->insertRecordData($arr, RKN_USER);
                $emailModel = new Application_Model_Email();
                $siteConfig = Zend_Registry::get('SITE_CONFIG');
                $fromEmail = $siteConfig['site_email'];
                $fromName = $siteConfig['site_name'];
                $subject = "Thanks for joining us";
                $url = APPLICATION_URL . "/index/index/tokenId/" . sha1($uid);
                $message = "
				Hi " . $arr['first_name'] . " " . $arr['last_name'] . ",
				<br>
				Thanks for signing up and welcome to the Raeken community!
				<br>
				We'd love to hear from you at " . $fromEmail . " please <a href='" . $url . "'>Click Here</a> to activate your account.
				<br>
				Happy Shopping.
				<br>
				The Raeken Team
				<br>			
				";

                $message = "Congragulations! <br> your email is registered. We will let you know when we go live";

                if (IS_LIVE)
                    $emailModel->sendMail($arr['user_email'], $fromEmail, $fromName, $subject, $message);
            }
            die;
        }

        public function posttotwitterAction()
        {
            require_once(APPLICATION_PATH . '/../assets/twitteroauth/twitteroauth.php'); //Path to twitteroauth library
            $consumerkey = TWITTER_APP_ID;
            $consumersecret = TWITTER_SECRET_ID;
            $accesstoken = "1898087952-hR19dDTppF115EOvALnE7HoM2AGFdwnhWUwewQk";
            $accesstokensecret = "nJY9kQOyzW0e6YOmR2piuE622wy4y3J5TjIovtANl64cI";
// start connection
            $connection = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
//message
            $message = "This is just to test that it working";
//send message
            $connection->post('https://api.twitter.com/1.1/statuses/update.json', array('status' => $message));
            die;
        }

        public function contactusAction()
        {
            $this->_helper->layout->disableLayout();
            $form = new Application_Form_ContactForm();
            $form->setAction("");
            $this->view->form = $form;
            $this->view->success = FALSE;
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $user_first_name = trim($arr["user_first_name"]);
                $user_last_name = trim($arr["user_last_name"]);
                $full_name = $user_first_name . " " . $user_last_name;
                $user_email = trim($arr["user_email"]);
                $message = trim($arr["message"]);
                $subject = "New message received";
                $email_model = new Application_Model_Email();
                //$email_model->sendMail(SITE_EMAIL, $user_email, $full_name, $subject, $message);
                if ($_SERVER["REMOTE_ADDR"] != "127.0.0.1")
                    $email_model->sendMail("marketing@raeken.com", $user_email, $full_name, $subject, $message);
                $this->_helper->FlashMessenger(
                        array('success' => '<strong>Success!</strong> Your message has been sent')
                );
                $this->view->success = TRUE;
            }
        }

        public function settingsAction()
        {
            $this->_helper->layout()->disableLayout();
            $form = new Application_Form_SettingForm();
            $form->setAction("");
            $form->setMethod("post");
            $form->getElement("submit")->setLabel("Save");
            $flag = array();

//            $user_id = $this->user_id;
            $user_id = "2";
            $model = new Application_Model_Common();
            $record = $model->getdata(RKN_USER, "rkn_uid = $user_id");
            unset($record["password"]);
            $form->populate($record);
            $this->view->signupForm = $form;

            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                unset($arr["submit"], $arr["MAX_FILE_SIZE"]);

                if (!empty($arr["password"]))
                {
                    $arr["password"] = md5($arr["password"]);
                    $model->updateRecordData($arr, "rkn_uid = $user_id", RKN_USER);
                }
                else
                {
                    unset($arr["password"]);
                    $model->updateRecordData($arr, "rkn_uid = $user_id", RKN_USER);
                }

                if (!empty($_FILES))
                {
                    $source = $_FILES["photo"]["tmp_name"];
                    $img_new_name = md5(time() . "user") . ".jpg";
                    $destination = "assets/images/users/" . $img_new_name;
                    $width = USERS_IMG_WIDTH;
                    $height = USERS_IMG_HEIGHT;

                    $img = new Application_Plugin_SimpleImage();
                    $img->load($source);
                    if ($height == NULL || empty($height))
                    {
                        $img->resizeToWidth($width);
                    }
                    else
                    {
                        $img->resize($width, $height);
                    }
                    $img->save($destination);

                    $model->updateRecordData(array("photo" => $img_new_name), "rkn_uid=$user_id", RKN_USER);
                }

                $flag['error'] = false;
                $flag['success'] = true;
                $flag['message'] = "<strong>Success!</strong><br>
                                            Account details updated successfully.";
                $this->view->assign($flag);
            }
        }

        public function socialpopupAction()
        {
            $this->_helper->layout->disableLayout();
            $this->renderScript("popup/social-popup.phtml");
        }

        public function socialtestAction()
        {
            $this->_helper->layout->disableLayout();
//            prd($this->getFacebookStatusUpdates(FACEBOOK_USERNAME));
            $this->view->facebookFeeds = $this->getFacebookStatusUpdates(FACEBOOK_USERNAME);
            $this->view->twitterFeeds = $this->getTwitterUpdates(TWITTER_USERNAME);
            $this->renderScript("extra/social-test.phtml");
        }

        public function getFacebookStatusUpdates($pageid = FACEBOOK_USERNAME, $postCount = "2", $startFrom = "1")
        {
            $appid = FACEBOOK_APP_ID;
            $secret = FACEBOOK_SECRET_ID;

            $feed = @file_get_contents('https://graph.facebook.com/' . $pageid . '/feed?access_token=' . $appid . '|' . $secret);
            $jsonData = json_decode($feed);
            $result = @(array) $jsonData->data;

            $new_array = array();
            $i = $startFrom;
            $newPostCount = "0";
            for ($i = $startFrom; $i <= $postCount; $i++)
            {
                $value = $result[$i];
                if (isset($value->message))
                {
                    $new_array[] = array(
                        "from" => $value->from->name,
                        "message" => $value->message,
                        @"picture" => getFacebookImageSource($value->from->id),
//                        @"picture" => $value->picture,
                        "updated_time" => $value->updated_time,
                        "likes" => @count($value->likes->data),
                        "comments" => @count($value->comments->data),
                    );
                    $newPostCount++;
                    if ($newPostCount == $postCount)
                        break;;
                }
            }

            return $new_array;
        }

        public function getTwitterUpdates($screen_name = TWITTER_USERNAME, $tweet_count = "2")
        {
            require_once APPLICATION_PATH . "/../assets/twitteroauth/twitteroauth.php";

            $twitteruser = $screen_name;
            $notweets = $tweet_count;
            $consumerkey = TWITTER_APP_ID;
            $consumersecret = TWITTER_SECRET_ID;

            $connection = new TwitterOAuth($consumerkey, $consumersecret);
            $tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets);
//            prd($tweets);

            $new_array = array();
            foreach ($tweets as $key => $value)
            {
                $new_array[] = array(
                    "message" => $value->text,
                    "created_time" => $value->created_at,
                    "screen_name" => $screen_name
                );
            }

            return $new_array;
        }

        public function signupfacebookAction()
        {
            $plugin = new Application_Plugin_SocialPlugin();
            $facebook_auth = $plugin->facebookLogin();
            $login_url = $facebook_auth["login_url"];
            $this->_redirect($login_url);
        }

        public function signuptwitterAction()
        {
            $plugin = new Application_Plugin_SocialPlugin();
            $twitter_auth = $plugin->twitterLogin();
            $login_url = $twitter_auth["login_url"];
            $this->_redirect($login_url);
        }

        public function headerAction()
        {
            $this->_helper->layout->disableLayout();
            $this->view->setScriptPath("application/layouts/scripts/");
            $this->_helper->getHelper('viewRenderer')->renderScript("header.phtml");
        }

        public function mobileheaderAction()
        {
            $this->_helper->layout->disableLayout();
            //$this->view->setScriptPath("application/views/scripts/mobile/");
            $this->_helper->getHelper('viewRenderer')->renderScript("mobile/wheader.phtml");
        }

        public function footerAction()
        {
            $this->_helper->layout->disableLayout();
            $this->view->setScriptPath("application/layouts/scripts/");
            $this->_helper->getHelper('viewRenderer')->renderScript("wfooter.phtml");
        }

        public function mobilefooterAction()
        {
            $this->_helper->layout->disableLayout();
            //$this->view->setScriptPath("application/views/scripts/mobile/");
            $this->_helper->getHelper('viewRenderer')->renderScript("mobile/wfooter.phtml");
        }

    }